﻿using System;
using System.Windows;
using System.Reflection;

namespace EasySL.Share
{
    public static class Extensions
    {
        public static T ConvertTo<T>(this object obj)
        {
            object result;
            try
            {
                result = Convert.ChangeType(obj, typeof(T), null);
            }
            catch
            {
                result = default(T);
            }

            return (T)result;
        }

        public static string Left(this string str, int length)
        {
            string s = "...";
            if (str.Length > length)
                return str.Substring(0, length - s.Length) + s;
            else
                return str;
        }

        public static UIElement Clone(this UIElement source)
        {
            UIElement cloned = (UIElement)Activator.CreateInstance(source.GetType());

            foreach (PropertyInfo curPropInfo in source.GetType().GetProperties())
            {
                if (curPropInfo.GetGetMethod() != null && (curPropInfo.GetSetMethod() != null))
                {
                    // Handle Non-indexer properties
                    if (curPropInfo.Name != "Item")
                    {
                        // get property from source
                        object getValue = curPropInfo.GetGetMethod().Invoke(source, new object[] { });

                        // clone if needed
                        if (getValue != null && getValue is UIElement)
                            getValue = Clone((UIElement)getValue);

                        // set property on cloned
                        curPropInfo.GetSetMethod().Invoke(cloned, new object[] { getValue });
                    }
                    // handle indexer
                    else
                    {
                        // get count for indexer
                        int numberofItemInColleciton = (int)curPropInfo.ReflectedType.GetProperty("Count").GetGetMethod().Invoke(source, new object[] { });

                        // run on indexer
                        for (int i = 0; i < numberofItemInColleciton; i++)
                        {
                            // get item through Indexer
                            object getValue = curPropInfo.GetGetMethod().Invoke(source, new object[] { i });

                            // clone if needed
                            if (getValue != null && getValue is DependencyObject)

                                getValue = Clone((UIElement)getValue);

                            // add item to collection
                            curPropInfo.ReflectedType.GetMethod("Add").Invoke(cloned, new object[] { getValue });

                        }
                    }
                }
            }
            return cloned;
        }
    }
}
